package cn.liumouren.jzxd.aspect;

import cn.hutool.extra.servlet.ServletUtil;
import cn.liumouren.jzxd.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author Daniel Liu
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(* cn.liumouren.jzxd.controller.*Controller.*(..))")
    public void pointcut() {
    }

    @Before(value = "pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String ip = ServletUtil.getClientIP(request);
        log.info("remote:: {} 开始执行: {}", ip, joinPoint.toString());
        log.info("参数为: {}", Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "retObj", pointcut = "pointcut()")
    public void doAfterReturning(R retObj) {
        // 执行 return 之前
        log.info("执行完返回的信息为: {}", retObj.get("msg"));
    }

    @AfterThrowing(value = "pointcut()")
    public void doAfterThrowing(JoinPoint joinPoint) {
        // 出现异常
        log.error("执行方法 {} 出现异常!", joinPoint.getSignature().getName());
    }

}
